指標作為函式參數(想修改呼叫端的指標):
如果你想在函式內改變呼叫端的指標本身(例如讓呼叫端指向新 malloc 出來的記憶體),需要用 指向指標 的指標(pointer to pointer)。
範例(在函式內分配):
void allocate_array(int **p, int n) {
*p = malloc(n * sizeof **p);
if (p == NULL) { / handle error */ }
}
int main() {
int *arr = NULL;
allocate_array(&arr, 10); // 傳入 arr 的位址
// 使用 arr...
free(arr);
}